'use client';

import React from 'react';
import { EventModel } from '../lib/api';
import { API_BASE_URL, API_TOKEN } from '../lib/config';

interface Props {
  event: EventModel | null;
  onClose: () => void;
}

export function AttachmentsViewer({ event, onClose }: Props) {
  if (!event) return null;
  const base = API_BASE_URL.replace(/\/$/, '');
  return (
    <div className="drawer">
      <div className="drawer-content">
        <header>
          <h2>Attachments for {event.id}</h2>
        </header>
        {event.attachments.length === 0 && <p className="muted">No attachments.</p>}
        <ul className="attachments-list">
          {event.attachments.map(file => {
            const href = `${base}/api/v1/owners/${event.owner}/attachments/${event.id}/${encodeURIComponent(file)}`;
            const headers = API_TOKEN ? { 'X-AW-Token': API_TOKEN } : undefined;
            return (
              <li key={file}>
                <a href={href} target="_blank" rel="noreferrer" onClick={e => {
                  if (headers) {
                    e.preventDefault();
                    fetch(href, { headers }).then(async res => {
                      const blob = await res.blob();
                      const url = URL.createObjectURL(blob);
                      const anchor = document.createElement('a');
                      anchor.href = url;
                      anchor.download = file;
                      anchor.click();
                      URL.revokeObjectURL(url);
                    });
                  }
                }}>
                  {file}
                </a>
              </li>
            );
          })}
        </ul>
        <footer>
          <button className="ghost" onClick={onClose}>Close</button>
        </footer>
      </div>
    </div>
  );
}
